package cn.wyu.blogrest.controller;

import cn.wyu.blogrest.entity.Status;
import cn.wyu.blogrest.entity.User;
import cn.wyu.blogrest.repository.AuthRepository;
import cn.wyu.blogrest.repository.StatusRepository;
import cn.wyu.blogrest.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by ajinlong on 2021/10/26.
 */

@RestController
@RequestMapping(value = "/timeline")
@Transactional
public class TimelineController {
    @Autowired
    private StatusRepository statusRepository;

    @Autowired
    private AuthRepository authRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 广场时间线
     */

    @RequestMapping(value = "/public")
    public List<Status> timelinePublic(){
        return this.statusRepository.findByOrderByCreateTimeDesc();
    }

    /**
     * 我的时间线
     */
    @RequestMapping(value = "/home")
    public List<Status> timelineHome(@RequestHeader("accessToken") String accessToken){
        User user = this.authRepository.findFirstByAccessToken(accessToken).getUser();
        Set<User> users = new HashSet<>(user.getFriends());
        users.add(user);
        return this.statusRepository.findFrendsAndMyStatus(users);
    }

    /**
     * 某用户时间线
     */
    @RequestMapping(value = "/user/{userId}")
    public List<Status> timelineUser(@PathVariable int userId){
        User user = this.userRepository.findById(userId);
        return this.statusRepository.findByUserOrderByCreateTimeDesc(user);
    }

}
